package cn.wolfcode.education.web.controller;

import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.service.IEmployeeService;
import cn.wolfcode.education.util.Code;
import cn.wolfcode.education.util.JSONResult;
import cn.wolfcode.education.util.MailUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;


@Controller
@RequestMapping("retrieve")
public class RetrieveController {

    @Autowired
    private IEmployeeService employeeService;

    //登陆  定位到登录页面
    @RequestMapping("retrieve")
    public String retrieve() {
        System.out.println("***************修改密码页面定位*************");
        return "retrieve";
    }

    /*用户名错误提示*/
    @RequestMapping("checkName")
    @ResponseBody
    public JSONResult checkNmae(String username) throws IOException {
        JSONResult jsonResult = new JSONResult();
        Employee employee = employeeService.retrieveSelectEmployee(username);
        if (employee == null) {
            jsonResult.setMsg("用户名不存在");
            return jsonResult;
        }
        return jsonResult;
    }

    //邮箱
    @RequestMapping("checkEmail")
    @ResponseBody
    public Code checkEmail(String email) throws IOException {
        //用户输入邮箱后获取的的验证码
        Code codes = new Code();
        codes.setCodeCheck(MailUtil.sendEamilCode(email));
        System.out.print(codes.getCodeCheck());
        return codes;
    }

    //验证码
    @RequestMapping("checkCode")
    @ResponseBody
    public JSONResult checkCode(Code codes, String code) throws IOException {
        JSONResult jsonResult = new JSONResult();
        //获取系统验证码
        String systemCode = codes.getCodeCheck();
        System.out.print(codes.getCodeCheck());

        if (systemCode != code) {
            jsonResult.setMsg("验证码错误");
            return jsonResult;
        }
        return jsonResult;
    }

    //忘记密码后修改密码
    @RequestMapping("save")
    @ResponseBody
    public JSONResult save(String username, String newpassword) throws IOException {
        JSONResult jsonResult = new JSONResult();
        if (username != null) {
            Employee employee = employeeService.retrieveSelectEmployee(username);
            if (employee == null || newpassword == null) {
                jsonResult.setMsg("账户错误或密码为空");
            } else {
                Employee employee1 = (Employee) SecurityUtils.getSubject().getPrincipal();
                employeeService.updatePassword(employee.getUsername(), newpassword);
            }
        }
        return jsonResult;
    }
}
